<template>
  <YsRow>
    <div class="preview-imgs border_style">
      <p class="preview-title text_01">{{imgTitle||'检测部位及缺陷位置实物图'}}：</p>
      <div v-for="(item,index) in imgsBody" :class="{'mark':item.values[0].is_mark===1,'on_marked':item.values[0].is_mark!=1}" class="sign">
        <div class=" img-box" v-if="item.values[0].is_mark===1">
          <div v-for="(it, index) in item.fileFlawInfos" :key="index" class="rectangleList" :style="{left:`${it.label_left_x}px`,top:`${it.label_left_y}px`}">
            <p class="titleFlaw">{{it.flaw_type_name}}</p>
            <div class="shape" :style="{width:`${it.width}px`,height:`${it.height}px`}"> </div>
          </div>
        </div>
        <img class="preview-bg" @load="loadImage" :src="item.values[0].value|getImgPath(index) ">
      </div>
    </div>
  </YsRow>
</template>
<script>

import { mapGetters, mapActions } from "vuex";

function getImageBase64(image, index) {
  const canvas = document.createElement('canvas')
  canvas.width = image.width
  canvas.height = image.height
  if (document.querySelectorAll(`#three${that.fileId} .sign .preview-bg`)[index]) {
    document.querySelectorAll(`#three${that.fileId} .sign .preview-bg`)[index].style.width = `${image.width}px`
    document.querySelectorAll(`#three${that.fileId} .sign .preview-bg`)[index].style.height = `${image.height}px`
  }
  const ctx = canvas.getContext('2d')
  ctx.drawImage(image, 0, 0, image.width, image.height)
  // 获取图片后缀名
  const extension = image.src.substring(image.src.lastIndexOf('.') + 1).toLowerCase()
  // 某些图片 url 可能没有后缀名，默认是 png
  return canvas.toDataURL('image/' + extension, 1)
}
let that
export default {
  name: 'previewThreeImgs',
  props: {

    fileId: {
      type: [Number, String],
      default: () => {
        return ""
      }
    },
    canvasItem: {
      type: Object,
      default: () => {
        return {}
      }
    },
    templateBean: {
      type: Object,
      default: () => {
        return {}
      }
    },
    reportDataBean: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  beforeCreate() {
    that = this
  },
  filters: {
    getImgPath(path, index) {
      const image = new Image()
      // 添加时间戳，防止浏览器缓存图片
      image.src = `${window.GlobalConfig.serviceProxy.BaseUrl}${path}` + '?timestamp=' + new Date().getTime()
      // 设置 crossOrigin 属性，解决图片跨域报错
      image.setAttribute('crossOrigin', 'Anonymous')
      image.onload = () => {
        let arr = Array.from(document.querySelectorAll(`#three${that.fileId} .preview-bg`));
        if (arr.length > 0) {
          document.querySelectorAll(`#three${that.fileId} .preview-bg`)[index].src = getImageBase64(image, index)
        }
      };
    },
  },
  watch: {
    //获取表头
    templateBean(v) {
      if (v && v.templateFields3) {
        this.imgTitle = v.templateFields3[0].field_name
      }
    },
    //获取表格body
    reportDataBean(v) {
      if (v && v.table_field_data3) {
        this.imgsBody = v.table_field_data3.map((v, index) => { return { ...v, fileFlawInfos: [] } })
        this.getImgDetail()
      }
    }
  },
  data() {
    return {
      imgTitle: "",
      imgsBody: []
    }
  },
  methods: {
    ...mapActions(['getDetectImgDetail']),
    //获取当前页面标注
    getImgDetail() {
      this.getDetectImgDetail({ file_id: this.fileId }).then(async res => {
        let { data, msg, scode, status } = res;
        if (status === 'ok') {
          this.imgsBody[0].fileFlawInfos = await this.setParticle(data.fileFlawInfos)
        }
      })
    },
    //设置文件地址
    setParticle(data) {
      let newdata = data.map(v => {
        return { ...v, width: v.label_right_x - v.label_left_x, height: v.label_right_y - v.label_left_y }
      })
      return newdata
    },
    //获取图片宽高
    getImageWidth() {
      let imgWrapper = document.querySelector(`#three${that.fileId} .mark .preview-bg`);
      if (imgWrapper) {
        document.querySelector(`#three${that.fileId} .mark`).style.width = `${document.querySelector(`#three${that.fileId} .mark .preview-bg`).clientWidth + 2}px`
        document.querySelector(`#three${that.fileId} .mark`).style.height = `${document.querySelector(`#three${that.fileId} .mark .preview-bg`).clientHeight + 2}px`
      }
    },
    //加载完成
    loadImage() {
      if (this.imgSrc !== '') {
        this.getImageWidth();
      }
    },
    //下载图片
    downloadImage(url, index) {
      let _this = this
      return new Promise((resolve) => {
        const image = new Image()
        // 添加时间戳，防止浏览器缓存图片
        image.src = url + '?timestamp=' + new Date().getTime()
        // 设置 crossOrigin 属性，解决图片跨域报错
        image.setAttribute('crossOrigin', 'Anonymous')
        image.onload = () => {
          let dataURL = _this.getImageBase64(image, index)
          resolve(dataURL);
        };
      });
    },
  },

}
</script>
<style scoped lang='less'>
.preview-imgs {
  // height: 500px;
  margin-top: 80px;
  padding-bottom: 50px;
  border: 1px solid #ccc;
  overflow: auto;
  .sign {
    margin-bottom: 50px;
    overflow: auto;
  }
  .mark {
    margin: 0 auto;
    position: relative;
  }
  .on_marked {
    img {
      margin: 0 auto;
    }
  }
  .preview-title {
    font-size: 16px;
    font-family: PingFang SC;
    font-weight: 400;
    line-height: 22px;
    color: #405580;
    margin: 24px 0 0 18px;
  }
  .preview-bg {
    display: block;
  }
  .img-box {
    border: 1px solid transparent;

    position: absolute;
    height: 100%;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    z-index: 999;
    .dlcvno {
      position: absolute;
      top: 20px;
      right: 20px;
      font-size: 32px;

      span {
        font-size: 22px;
        margin-top: -4px;
      }

      // font-weight: bold   ;
    }

    .rectangleList {
      position: absolute;
      margin-left: -8px;
      .titleFlaw {
        margin-top: -20px;
        color: #d53939;
      }
    }

    .shape {
      width: 10px;
      height: 10px;
      border: 1px solid #d53939;
      // background: #d5393941;
    }
  }
}
</style>
